package com.ch.forum.utils;

import com.ch.forum.constants.HttpConstants;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Random;

public class WxUtils {

    /**
     * 获取随机字符串
     * @return
     */
    public static String create_nonce_str() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += chars.charAt(rd.nextInt(chars.length() - 1));
        }
        return res;
    }

    /**
     * POST请求，字符串形式数据
     * @param url 请求地址
     * @param param 请求数据
     * @param charset 编码方式
     */
    public static String sendPostUrlParam(String url, String param, String charset) {

        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        String line;
        URL realUrl;
        URLConnection conn;
        try {
            realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty(HttpConstants.REQUEST_ACCEPT,
                    HttpConstants.REQUEST_ACCEPT_VALUE);
            conn.setRequestProperty(HttpConstants.REQUEST_CONNECTION,
                    HttpConstants.REQUEST_CONNECTION_VALUE);
            conn.setRequestProperty(HttpConstants.REQUEST_USER_AGENT,
                    HttpConstants.REQUEST_USER_AGENT_VALUE);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), charset));
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }


    public static String maptoXml(Map<String,Object> map){
        StringBuilder sb = new StringBuilder();

        if(map != null){
            sb.append("<xml>");
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append("</").append(entry.getKey()).append(">");
            }
            sb.append("</xml>");
        }
        return sb.toString();
    }

    /**
     * 统一下单获取签名
     * @param map
     * @param key
     * @return
     */
    public static String getSign(Map<String,Object> map,String key){
        String string1 = paramStr(map);
        String stringSignTemp = string1 + "&key=" + key;
        String signValue = MD5.getMD5Code(stringSignTemp).toUpperCase();
        System.out.println("生成的sign：" + signValue);
        return signValue;

    }

    /**
     * 返回H5支付获取签名
     * @param map
     * @param key
     * @return
     */
    public static String getPaySign(Map<String,Object> map,String key){
        String string1 = payParamStr(map);
        String stringSignTemp = string1 + "&key=" + key;
        System.out.println("返回前台签名的字符串：" + stringSignTemp);
        String signValue = MD5.getMD5Code(stringSignTemp).toUpperCase();
        return signValue;

    }

    public static String payParamStr(Map<String,Object> map){
        StringBuilder sb = new StringBuilder();

        sb.append("appId=").append(map.get("appId")).append("&");
        sb.append("nonceStr=").append(map.get("nonceStr")).append("&");
        sb.append("package=").append(map.get("package")).append("&");
        sb.append("signType=").append(map.get("signType")).append("&");
        sb.append("timeStamp=").append(map.get("timeStamp"));

        return sb.toString();
    }

    public static String paramStr(Map<String,Object> map){
        StringBuilder sb = new StringBuilder();

        sb.append("appid=").append(map.get("appid")).append("&");
        sb.append("body=").append(map.get("body")).append("&");
        sb.append("mch_id=").append(map.get("mch_id")).append("&");
        sb.append("nonce_str=").append(map.get("nonce_str")).append("&");
        sb.append("notify_url=").append(map.get("notify_url")).append("&");

        sb.append("out_trade_no=").append(map.get("out_trade_no")).append("&");
        sb.append("product_id=").append(map.get("product_id")).append("&");
        sb.append("spbill_create_ip=").append(map.get("spbill_create_ip")).append("&");
        sb.append("total_fee=").append(map.get("total_fee")).append("&");
        sb.append("trade_type=").append(map.get("trade_type"));

        return sb.toString();
    }
}
